package com.tj.jinzao.base;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


import com.tj.jinzao.R;
import com.tj.jinzao.common.Constant;
import com.tj.jinzao.common.Settings;
import com.tj.jinzao.utils.NetUtils;
import com.tj.jinzao.utils.ToastUtils;
import com.tj.jinzao.widgets.EmptyView;
import com.tj.jinzao.widgets.MyRecyclerView;


/**
 * 所有带刷新的RecyclerView的fragment基类
 * Created by wjy on 2016/3/25.
 */
public abstract class BaseListFragment<T, V extends BasePresenter> extends BaseFragment<V> implements RecyclerViewAdapter.OnItemClickListener, IBaseView<T> {

    //每页20条数据
    public static int ITEMS_NUM_PER_PAGE = 20;

    protected MyRecyclerView mListView;
    protected RecyclerView.Adapter mAdapter;
    protected View mTopView;
    protected EmptyView mEmptyView;
    protected LinearLayoutManager mLayoutManager;
    protected SwipeRefreshLayout mRefreshLayout;

    protected int mPageNo = 1;//当前页
    protected int mPageNum = 1;//总页数

    private int mLastVisibleItem = 0;

    protected final static String ARG_LOAD_ID = "load_id";

    protected int mLoaderId;//缓存列表时间id

    protected boolean mLoading, mInitialize = false, mMoveTop = false;
    protected boolean mRequestAuto = true;

    protected boolean mCanLoadMore = true; //控制没有更多数据的时候，禁用上拉更多

    private int mEmptyImageRes, mEmptyNetErrorRes;
   public View view;
//    private boolean mIsLoadMore = false;

    private boolean isTopUp;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mLayoutResId = getArguments().getInt(ARG_LAYOUT_RES_ID);
        mLoaderId = getArguments().getInt(ARG_LOAD_ID);
    }

    @Override
    public View onCreateView(LayoutInflater inflater
            , ViewGroup container, Bundle savedInstanceState) {
        view = super.onCreateView(inflater, container, savedInstanceState);
        if (view == null) {
            return null;
        }
        mListView = view.findViewById(R.id.my_list);
        mRefreshLayout = view.findViewById(R.id.my_refresh_layout);
        mLayoutManager = getLayoutManager();
        //给RecyclerView设置布局管理器
        mListView.setLayoutManager(mLayoutManager);
        mTopView = view.findViewById(R.id.top_view);
        if (mTopView != null) {
            mTopView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mListView != null) mListView.smoothScrollToPosition(0);
                }
            });
        }
        mEmptyView = view.findViewById(R.id.empty_view);

        if (mEmptyView != null) mEmptyView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mEmptyView != null && (mEmptyView.getState() == EmptyView.State.LOADING
                        || mEmptyView.getState() == EmptyView.State.NO_DATA)) {
                    return;
                }
                if (NetUtils.isConnected(getActivity())) {
                    setEmptyView(EmptyView.State.LOADING, true);
                    loadData(true, false);
                }
            }
        });
        if (mRefreshLayout != null) {
            mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    refresh();
                }
            });
            mRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
        }

        mListView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView,
                                             int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //解决未完全拉到底部弹出提示
                mLastVisibleItem = mLayoutManager.findLastCompletelyVisibleItemPosition();
                int completelyVisibleItem = mLayoutManager.findFirstCompletelyVisibleItemPosition();
                //判断是否已到顶部并且是滑动状态
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    isTopUp = false;
                }
                if (!recyclerView.canScrollVertically(-1) && completelyVisibleItem == 0 && newState == RecyclerView.SCROLL_STATE_IDLE && !isTopUp) {
                    setTopRefresh();
                    Log.d("baseactivity", "canScrollVertically");
                }
                if (newState == RecyclerView.SCROLL_STATE_IDLE && mCanLoadMore && canLoadMoreItems()
                        && mLastVisibleItem + 1 == mListView.getAdapter().getItemCount()&& mPageNo < mPageNum) {
//                    mRefreshLayout.setRefreshing(true);
                    loadMoreItems();
//                    if(!mIsLoadMore&&!mLoading) {
//                        if (mRefreshLayout != null)
//                            mRefreshLayout.setLoading(true);
//                        ToastUtils.showToast(mContext,"load start");
//                        mIsLoadMore = true;
//                        loadMoreItems();
//                    }
                } else if (recyclerView.computeVerticalScrollOffset() > 0 && !recyclerView.canScrollVertically(1)
                        && newState == RecyclerView.SCROLL_STATE_IDLE &&
                        mLastVisibleItem + 1 == mListView.getAdapter().getItemCount() && !mCanLoadMore) {
                    ToastUtils.showToast(mContext, "没有更多了");
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                isTopUp = dy < 0 ? false : true;
                if (mMoveTop) {
                    int firstPosition = mLayoutManager.findFirstVisibleItemPosition();
                    mTopView.setVisibility(firstPosition > 2 ? View.VISIBLE : View.INVISIBLE);
                }
                mLastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
                onScroll(recyclerView, dx, dy);
            }
        });
        mListView.setOnItemClickListener(this);
        createView(inflater, view);
        return view;
    }

    /**
     * 已滑动到顶部处理
     */
    protected void setTopRefresh() {
    }

    /**
     * 设置下拉刷新是否启用
     *
     * @param enable
     */
    protected void setRefreshEnable(boolean enable) {
        if (mRefreshLayout != null)
            mRefreshLayout.setEnabled(enable);
    }

    /**
     * RecycleView方向,默认垂直
     */
    protected LinearLayoutManager getLayoutManager() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        //垂直方向
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        return layoutManager;
    }

    /**
     * onCreateView 之后调用，主要是自定义对listView，emptyView，headView处理
     *
     * @param inflater
     * @param view
     */
    abstract protected void createView(LayoutInflater inflater, View view);

    protected void onScroll(RecyclerView recyclerView, int dx, int dy) {
    }

    //是否显示滑动到顶部
    protected void setTopEnable(boolean enable) {
        mMoveTop = enable;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mListView != null) mListView.setAdapter(null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        createActivity();
    }

    protected void createActivity() {
        if (mAdapter == null) {
            mAdapter = createAdapter();
            mListView.setAdapter(mAdapter);
            mListView.setOnItemClickListener(this);
        }
    }

    abstract protected RecyclerView.Adapter createAdapter();

    protected void setFooterVisibility() {
        if (mAdapter.getItemCount() == 0
                || mAdapter.getItemCount() % ITEMS_NUM_PER_PAGE != 0 || !canLoadMoreItems()) {
            mCanLoadMore = false;
        } else {
            mCanLoadMore = true;
        }
        if (Constant.TRACE) {
            Log.i(TAG, "Footer visible: "
                    + ", mPageNo:" + mPageNo + ", size:" + mListView.getAdapter().getItemCount() + ",mCanLoadMore:" + canLoadMoreItems());
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!mInitialize && mRequestAuto)
            loadData(false, false);
    }

    protected void setEmptyView(final EmptyView.State state, boolean isNeedWait) {
        if (mEmptyView == null && isNeedWait) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    setEmptyView(state, false);
                }
            }, 2000);
        } else {
            if (mEmptyView != null) {
                try {
                    if (mListView.getAdapter().getItemCount() > 0) {
                        return;
                    }
                } catch (NullPointerException e) {
                }
                if (EmptyView.State.NO_DATA == state) {
                    if (!NetUtils.isConnected(getActivity())) {
                        mEmptyView.setState(EmptyView.State.NETWORK_ERROR, mEmptyNetErrorRes);
                        return;
                    }
                }

                mEmptyView.setVisibility(View.VISIBLE);
                mEmptyView.setState(state, null);
                mListView.setVisibility(View.INVISIBLE);
            }

        }
    }

    protected void setEmptyView(String text) {
        if (mEmptyView != null) {
            if (TextUtils.isEmpty(text)) {
                text = "这里什么都没有";
            }
            if (!NetUtils.isConnected(getActivity())) {
                mEmptyView.setState(EmptyView.State.NETWORK_ERROR, text, mEmptyNetErrorRes);
                return;
            } else {
                mEmptyView.setVisibility(View.VISIBLE);
                mEmptyView.setState(EmptyView.State.NO_DATA, text, mEmptyImageRes);
            }
        }
    }

    protected boolean canLoadMoreItems() {
        return true;
    }

    protected void loadMoreItems() {
        loadData(false, true);
    }

    protected void refresh() {
        loadData(true, false);
    }

    public void loadData(boolean refresh, boolean loadMore) {
        //页数设置为0表示刷新
        if (refresh) mPageNo = 1;
        if (loadMore) mPageNo++;
        if (Constant.TRACE)
            Log.d(TAG, "refresh:" + refresh + ",loadMore:" + loadMore + "mLoaderId:" + mLoaderId);
        boolean request = canRequest(refresh, loadMore, 0);
        mInitialize = true;
        if (!request) {
            mPageNo = Settings.getTimeSharedPreferences(mContext).getInt(Settings.KEY_PREF_LIST_CURRENT_PAGE
                    + mLoaderId, 1);
            if (refresh) mPageNo = 1;
            if (!hasData()) {
                setEmptyDataView();
            }
        } else {
            setEmptyView(EmptyView.State.LOADING, false);
            mLoading = true;
            requestData();
        }
    }

    /**
     * list是否有数据
     *
     * @return
     */
    abstract protected boolean hasData();

    /**
     * 请求网络
     */
    abstract protected void requestData();

    /**
     * 内容为空时显示内容，需要listView设置emptyView
     */
    abstract protected void setEmptyDataView();

    @Override
    public void onRequestError(String message) {
        mLoading = false;
        //关闭加载
        closeRefresh();
        setEmptyView(EmptyView.State.NETWORK_ERROR, false);
    }

    @Override
    public void onRequestSuccess(T t) {
        closeRefresh();
        mLoading = false;
        if (mContext != null && resolveData(t)) {
            SharedPreferences.Editor editor = Settings.getTimeSharedPreferences(mContext).edit();
            editor.putLong(Settings.KEY_PREF_LIST_LAST_REQUEST + mLoaderId, System.currentTimeMillis());
            editor.putInt(Settings.KEY_PREF_LIST_CURRENT_PAGE + mLoaderId, mPageNo);
            editor.commit();
        }
    }

    protected void closeRefresh() {
        if (mRefreshLayout != null) mRefreshLayout.setRefreshing(false);
        //模拟耗时
//        if (mRefreshLayout != null) {
//            new Thread(){
//                @Override
//                public void run() {
//                    try {
//                        sleep(2000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    mContext.runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            if(mIsLoadMore){
//                                ToastUtils.showToast(mContext,"load finish");
//                                mRefreshLayout.setLoading(false);
//                                mIsLoadMore=false;
//                            }else{
//                                mRefreshLayout.setRefreshing(false);
//                            }
//                        }
//                    });
//                }
//            }.start();
//        }
    }

    /**
     * 解析json
     *
     * @param t
     * @return 返回true, 表示解析或存储成功，列表时间保存
     */
    abstract protected boolean resolveData(T t);

    /**
     * 是否可以联网请求
     *
     * @param refresh   //强制刷新
     * @param loadMore  //加载更多
     * @param spaceTime //间隔多久可以请求
     * @return
     */
    protected boolean canRequest(boolean refresh, boolean loadMore, long spaceTime) {
        if (refresh || loadMore) return true;
        long lastTime = Settings.getLongTime(mContext, Settings.KEY_PREF_LIST_LAST_REQUEST + mLoaderId, 0);
        if (spaceTime == 0) {
            if (NetUtils.isWifi(mContext)) {
                spaceTime = Constant.REQUEST_ONE_HOUR_TIME;
            } else {
                spaceTime = Constant.REQUEST_ONE_DAY_TIME / 2;
            }
        }
        return (lastTime == 0 || Math.abs(System.currentTimeMillis() - lastTime) > spaceTime);
    }


    protected void setEmptyNetErrorRes(int res) {
        this.mEmptyNetErrorRes = res;
    }

    protected void setEmptyImageRes(int res) {
        this.mEmptyImageRes = res;
    }

    protected void setEmptyTextView() {
        mEmptyView.setState(EmptyView.State.NO_DATA, "", mEmptyImageRes);
    }

    public boolean hasMoreItems() {
        return mCanLoadMore;
    }
}
